import api from './utils/api'
App({
  onLaunch() {
     //检测新版本
     this.updateManager()
     wx.getSystemInfo({
       success: e => {
        // console.log(e)
        let custom = wx.getMenuButtonBoundingClientRect();
        // console.log(e.statusBarHeight,custom)
        this.globalData.Custom = custom;
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
       }
     })
  },
  onShow(){
    const sessionKey = wx.getStorageSync('sessionKey')||''
    if(sessionKey)return
      wx.showModal({
        title: '提示',
        content: '授权登录',
        success: res=> {
          if (res.confirm) {
            this.doLogin()
            // console.log(this)
          } else if (res.cancel) {
          }
        }
      })
  },
  updateManager(){
    const updateManager = wx.getUpdateManager()
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            updateManager.applyUpdate()
          }
        }
      })
    })
  },
  globalData: {
    userInfo: null,
    CustomBar:null,
    Custom:null
  },
  api:api,
//登录
 doLogin(){
   wx.showLoading({
    title: '登录中',
  })   
        wx.login({
         success: async (datas) =>{
          // console.log('获取code：',datas)
          let result= await api.login({jsCode: datas.code})
           // console.log('获取key：',result)
           wx.setStorageSync('sessionKey', result.data.thirdSessionKey)
           wx.setStorageSync('openId', result.data.openId)
           wx.setStorageSync('userId', result.data.userId)
           wx.setStorageSync('Key', result.data.sessionKey)
           wx.setStorageSync('nickName',result.data.nickName)
           wx.setStorageSync('avatarUrl',result.data.headimgUrl)
           wx.hideLoading()
           wx.reLaunch({
            url:this.getCurrentPageUrlWithArgs()
          })
       }
     }) 
 },
  //获取当前页面带参数的url
  getCurrentPageUrlWithArgs(){
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
      const value = options[key]
      urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
  },
// 设置监听器
watch: function (ctx, obj) {
  Object.keys(obj).forEach(key => {
    this.observer(ctx.data, key, ctx.data[key], function (value) {
      obj[key].call(ctx, value)
    })
  })
},
// 监听属性，并执行监听函数
observer: function (data, key, val, fn) {
  Object.defineProperty(data, key, {
    configurable: true,
    enumerable: true,
    get: function () {
      return val
    },
    set: function (newVal) {
      if (newVal === val) return
      fn && fn(newVal)
      val = newVal
    },
  })
}
})
